package project.ydlChat.util;

import project.ydlChat.Message;

import java.io.*;
import java.util.Optional;

/**
 * @author 杜伟毅
 * @version 1.0
 * @since 2024/09/26
 * 工具类
 */
public class MsgUtils {
    /**
     * 从流中读取类msg
     *
     * @return 对函数返回值的描述
     * @author 杜伟毅
     * @since 2024/9/26 0026 23:28
     */
    public static Optional<Message> readMsg(InputStream inputStream) {
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(inputStream);
            //封装成一个Optional，将来外界使用时就可以避免空指针
            return Optional.ofNullable((Message) ois.readObject());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return Optional.empty();
    }

    /**
     * 往输出流中写msg
     *
     * @return 对函数返回值的描述
     * @author 杜伟毅
     * @since 2024/9/26 0026 23:28
     */
    public static void writeMsg(OutputStream outputStream, Message message) {
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(outputStream);
            oos.writeObject(message);
            //把流里的数据刷出去
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
